import { isDev } from "./config";
import { api } from "./service/ice/api";

const { ERR_LOG } = process.env;

require("express-async-errors");

process.on("unhandledRejection", (reason, p) => {
  console.log("unhandledRejection");
  throw reason;
});
let errorTimes = 0;
process.on("uncaughtException", (error) => {
  console.log(`==== uncaughtException ${++errorTimes} ====`);
  if (error instanceof Error) {
    // console.error(error.name + ':', error.message)
    const lines = error.stack
      .split("\n")
      .filter((v, i) => i < 6)
      .join("\n");
    console.log(lines);
  } else {
    console.log(error);
  }
});

function getErrInfo(error) {
  let errObj = {
    msg: "未知错误",
  };
  if (error instanceof Error) {
    let { name, message: msg, code } = error;
    msg = msg.replace("Validation error:", "校验错误：");
    // if(errors && errors[0]) msg += '：' + errors[0].message
    errObj = {
      msg,
      name,
      code,
    };
    if (error.response) {
      errObj = {
        ...errObj,
        ...error.response.data,
      };
    }
  } else if (typeof error == "string") {
    errObj = {
      msg: error,
      name: "tipErr",
    };
  } else if (error && typeof error == "object") {
    errObj = error;
    errObj.msg = error.message || error.msg;
    delete errObj.message;
  }
  return errObj;
}

export function catchError(app) {
  app.use((error, req, res, next) => {
    if (error) {
      // too many redirect错误时，重启试试
      if (isDev) {
        // console.log(error);
      }
      const obj = getErrInfo(error);
      // console.log(obj);
      if (obj.msg != "jwt malformed") {
        let code = 500;
        if (obj.code >= 400 && obj.code < 600) {
          code = obj.code;
        }
        res.status(code).send(obj);
        if (!obj.logged && ERR_LOG == 1) {
          api.postActLog({
            path: req.path,
            act: "err-log",
            ip: req.realIp,
            userId: req.user?.id,
            extra: {
              ...req._body,
              ...obj,
            },
          });
        }
        return;
      }
    }
    next(error);
  });
}
